<template>
  <div class="edit-page-wrap">
    <Head title="活动信息">
      <template #content>
        <el-form
          ref="ruleFormRef"
          :model="ruleForm"
          :rules="rules"
          label-width="100px"
          class="edit-form-wrap"
        >
          <el-form-item label="活动名称" prop="name">
            <el-input
              v-model.trim="ruleForm.name"
              placeholder="请输入活动名称"
              maxlength="30"
              clearable
            />
          </el-form-item>
          <el-form-item label="活动日期" prop="dates">
            <div class="edit-date-wrap">
              <el-date-picker
                v-model="ruleForm.dates"
                popper-class="qc-date"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                valueFormat="YYYY-MM-DD"
                format="YYYY-MM-DD"
                :disabled-date="disabledDate"
              />
            </div>
          </el-form-item>
          <el-form-item label="活动说明" prop="introduce">
            <el-input
              v-model.trim="ruleForm.introduce"
              placeholder="请输入活动说明"
              maxlength="200"
              type="textarea"
              :rows="3"
              show-word-limit
              clearable
            />
          </el-form-item>
        </el-form>
      </template>
    </Head>
    <Head title="活动配置">
      <template #tip>
        <div class="head-tip left-8">
          <div class="icon"></div>
          奖励示例：创建3级奖励梯度，分别对应的充值金额为100元、200元、300元，用户充值210元，平台下发200元对应的优惠券奖励。
        </div>
      </template>
      <template #content>
        <RechangeConfig
          ref="rechangeConfigRef"
          :activity-id="id"
        ></RechangeConfig>
        <el-form
          ref="ruleFormRef1"
          :model="ruleForm"
          :rules="rules"
          label-width="100px"
          class="edit-form-wrap"
        >
          <el-form-item
            label="可参与次数"
            prop="participatingCount"
            class="has-tips"
          >
            <el-input
              v-model.trim="ruleForm.participatingCount"
              placeholder="请输入可参与次数"
              maxlength="9"
              clearable
            />
            <div class="tip">
              <div class="icon"></div>
              活动期间，单用户最多可参与奖励的次数。
            </div>
          </el-form-item>
        </el-form>
      </template>
    </Head>
    <Head title="可参与用户">
      <template #content>
        <el-form
          ref="ruleFormRef2"
          :model="ruleForm"
          :rules="rules"
          label-width="100px"
          class="edit-form-wrap"
        >
          <el-form-item label="活动用户" prop="targetType" class="has-tips">
            <el-radio-group
              v-model="ruleForm.targetType"
              v-for="(item, index) in optionsS.targetType"
              :key="index"
              @change="handleTargetType"
            >
              <el-radio :label="item.value">{{ item.label }}</el-radio>
            </el-radio-group>
            <div class="tip">
              <div class="icon"></div>
              {{
                ruleForm.targetType === '0'
                  ? '所有用户均可参与活动'
                  : ruleForm.targetType === '1'
                  ? '选定企业后，该企业所有用户均可参与活动，含活动期间新增的用户'
                  : '选定标签后，该标签内所有均可参与活动，标签用户添加、删除会同步更新'
              }}
            </div>
          </el-form-item>
          <el-form-item
            v-if="ruleForm.targetType === '1'"
            label=""
            prop="treeVehicles"
          >
            <QcTree
              ref="treeVehiclesRef"
              :setCheckedKeys="ruleForm.treeVehicles"
              :data="optionsS.vehicle"
              :showCheckbox="true"
              :checkStrictly="true"
              @handleCheck="handleCheckVehicles"
            ></QcTree>
          </el-form-item>
          <el-form-item
            v-if="ruleForm.targetType === '2'"
            label=""
            prop="treeLabels"
          >
            <QcTree
              ref="treeLabelRef"
              :setCheckedKeys="ruleForm.treeLabels.split(',')"
              :data="optionsS.label"
              :showCheckbox="true"
              @handleCheck="handleCheckLabel"
            ></QcTree>
          </el-form-item>
        </el-form>
      </template>
    </Head>
    <div class="edit-btn-wrap">
      <el-button type="primary" plain @click="back">取消</el-button>
      <el-button type="primary" v-btnAntiShake="onSubmit">保存</el-button>
    </div>
  </div>
</template>

<script lang="ts" setup>
import Head from '@/components/head/index.vue';
import QcTree from '@/components/qcTree/index.vue';
import RechangeConfig from './rechangeConfig.vue';
import { FormInstance, FormRules } from 'element-plus';
import {
  saveUserActivity,
  updateUserActivity,
  getUserActivityById,
} from '@/service/apis/market';
import { queryDicByParent } from '@/service/apis/api';
import { queryVehicle, queryLabelListByName } from '@/service/apis/org';
import { IS_INT } from '@/utils/verify';

const router = useRouter();
const route = useRoute();
const {
  query: { id },
} = route;

const ruleFormRef = ref<FormInstance>();
const ruleFormRef1 = ref<FormInstance>();
const ruleFormRef2 = ref<FormInstance>();
const rechangeConfigRef = ref();
const treeVehiclesRef = ref();

const optionsS = reactive({
  org: [] as any,
  targetType: [] as any,
  vehicle: [] as any,
  label: [] as any,
});

const orgId = window.localStorage.getItem('orgId') || '';
queryDicByParent({
  listDtos: ['stationActivityTargetType'],
}).then((res: any) => {
  if (res) {
    if (orgId) {
      optionsS.targetType = res.stationActivityTargetType.filter(
        (item: any) => item.value !== '0'
      );
      ruleForm.targetType = '1';
    } else {
      optionsS.targetType = res.stationActivityTargetType;
    }
  }
});

// 获取车辆机构
const getVehicle = () => {
  queryVehicle({}).then((res: any) => {
    if (res) {
      optionsS.vehicle = res;
    }
  });
};

// 获取标签
const getLabel = () => {
  queryLabelListByName({}).then((res: any) => {
    if (res) {
      optionsS.label = res.listMap;
    }
  });
};

const ruleForm = reactive({
  name: '', // 优惠券名称

  dates: [] as any, // 活动日期
  // startTime: '', // 活动开始时间
  // endTime: '', // 活动结束时间

  introduce: '', //活动说明

  participatingCount: '', //可参与次数

  targetType: '0', //活动用户
  targetIds: '', //活动用户ids
  treeVehicles: [] as any, //活动用户-机构树
  treeLabels: '', //活动用户-标签树
});

const disabledDate = (time: any) => {
  return time.getTime() < new Date(new Date().toLocaleDateString()).getTime();
};
const checkTreeVehicles = (rule: any, value: any, callback: any) => {
  const arr: any = [];
  const treeOrg = treeVehiclesRef.value?.getCheckedNodes();
  treeOrg.forEach((item: any) => {
    if (item.type !== 'CHANNEL') {
      arr.push(item.id);
    }
  });
  if (arr.length === 0) {
    callback(new Error('请选择具体的用户企业（车辆机构）'));
  }
  callback();
};
const rules = reactive<FormRules>({
  name: [{ required: true, message: '请输入活动名称', trigger: 'blur' }],
  dates: [
    { required: true, message: '请选择活动日期', trigger: ['blur', 'change'] },
  ],
  introduce: [{ required: true, message: '请输入活动说明', trigger: 'blur' }],
  participatingCount: [
    { required: true, message: '请输入可参与次数', trigger: 'blur' },
    {
      pattern: IS_INT,
      message: '请输入正确的可参与次数，正整数',
      trigger: 'blur',
    },
  ],
  targetType: [
    { required: true, message: '请选择活动用户', trigger: ['blur', 'change'] },
  ],
  treeVehicles: [
    { required: true, message: '请选择企业', trigger: ['blur', 'change'] },
    { validator: checkTreeVehicles, trigger: ['blur', 'change'] },
  ],
  treeLabels: [
    { required: true, message: '请选择标签', trigger: ['blur', 'change'] },
  ],
});

const handleTargetType = (val: any) => {
  if (val === '1' && optionsS.vehicle.length === 0) {
    getVehicle();
  } else if (val === '2' && optionsS.label.length === 0) {
    getLabel();
  }
};

const handleCheckVehicles = (
  data: any,
  checkedData: any,
  checkedChildData: any
) => {
  ruleForm.treeVehicles = checkedChildData;
};
const handleCheckLabel = (
  data: any,
  checkedData: any,
  checkedChildData: any
) => {
  ruleForm.treeLabels = checkedChildData.toString();
};

if (id) {
  getUserActivityById(id).then((res: any) => {
    if (res) {
      ruleForm.name = res.name;
      ruleForm.introduce = res.introduce;
      ruleForm.dates = [res.startTime, res.endTime];

      ruleForm.participatingCount = res.participatingCount;
      ruleForm.targetType = String(res.targetType);

      rechangeConfigRef.value?.setData(res.detailMap);

      // 用户树
      if (ruleForm.targetType === '1') {
        ruleForm.treeVehicles = res.targetIds.split(',');
        getVehicle();
      } else if (ruleForm.targetType === '2') {
        ruleForm.treeLabels = res.targetIds;
        getLabel();
      }
    }
  });
} else {
  if (orgId) {
    getVehicle();
  }
}

const back = () => {
  router.go(-1);
};

const emit = defineEmits(['clear-cache']);
const onSubmit = async () => {
  if (!ruleFormRef.value || !ruleFormRef1.value || !ruleFormRef2.value) return;
  let flag = true;
  let objError = {} as any;
  let comData = [] as any;
  try {
    comData = await Promise.all([
      ruleFormRef.value.validate((e: any, fields: any) => {
        flag = flag ? e : false;
        if (!e) {
          objError = { ...objError, ...fields };
        }
      }),
      rechangeConfigRef.value?.getData(),
    ]);
  } catch (e) {}
  if (!flag) {
    for (const key in ruleForm) {
      if (objError[key]) {
        ruleFormRef.value.scrollToField(key);
        break;
      }
    }
  }
  try {
    await Promise.all([
      ruleFormRef1.value.validate((e: any, fields: any) => {
        flag = flag ? e : false;
        if (!e) {
          objError = { ...objError, ...fields };
        }
      }),
      ruleFormRef2.value.validate((e: any, fields: any) => {
        flag = flag ? e : false;
        if (!e) {
          objError = { ...objError, ...fields };
        }
      }),
    ]);
  } catch (e) {}
  if (!flag || !comData[1]) {
    for (const key in ruleForm) {
      if (objError[key]) {
        ruleFormRef1.value.scrollToField(key);
        ruleFormRef2.value.scrollToField(key);
        break;
      }
    }
    return;
  }

  const form: any = {
    type: 2,
    name: ruleForm.name,
    startTime: ruleForm.dates[0],
    endTime: ruleForm.dates[1],
    introduce: ruleForm.introduce,
    qualifiedType: 1,
    detailMap: comData[1],
    participatingCount: ruleForm.participatingCount,
    stationType: 0,
    targetType: ruleForm.targetType,
  };
  // 用户数
  form.targetIds = '';
  if (ruleForm.targetType === '1') {
    // form.targetIds = ruleForm.treeVehicles;
    const arr: any = [];
    const treeOrg = treeVehiclesRef.value?.getCheckedNodes();
    treeOrg.forEach((item: any) => {
      if (item.type !== 'CHANNEL') {
        arr.push(item.id);
      }
    });
    form.targetIds = arr.toString();
  } else if (ruleForm.targetType === '2') {
    form.targetIds = ruleForm.treeLabels;
  }
  // form.targetIds =
  //   ruleForm.targetType === '1'
  //     ? ruleForm.treeVehicles
  //     : ruleForm.targetType === '2'
  //     ? ruleForm.treeLabels
  //     : '';

  console.log('form---', form, comData);
  if (id) {
    form.id = id;
    updateUserActivity(form).then((res: any) => {
      emit('clear-cache');
      back();
    });
  } else {
    saveUserActivity(form).then((res: any) => {
      emit('clear-cache');
      back();
    });
  }
};
</script>